<?php
/**
 *
 *
 */
namespace Yz\modules\Generic;

use Yz_Array,
    Yz_Hash;

abstract class Controller_AbstractUpdate
    extends Controller_AbstractFetch
{

    /**
     *  @var Yz_Hash
     */
    protected $postData;

    protected $error;
    protected $success;

    /******************************
     *      Public methods        *
     ******************************/

    /**
     *
     */
    public function doPost(Yz_Array $args, Yz_Hash $post)
    {
        $this->postData = $post;
        return $this
            ->checkAccess()         // method of Yz_Controller_Templated
            ->parseArguments($args) // method of Controller_AbstractFetch
            ->fetchData()           // method of Controller_AbstractFetch
            ->processData($post)
            ->updateModel()
            ->output()              // method of Yz_Controller_Templated
        ;
    }


    /******************************
     *     Protected methods      *
     ******************************/


    /** process the fetched data and the POST input
     *  @param Yz_Hash $post
     *  @return this
     */
    protected function processData(Yz_Hash $post)
    {
        return $this;
    }


    /**
     *  @return this
     *
     */
    protected function updateModel()
    {
        debug();
        if (null === $this->error) {
            try {
                $this->item->save();
                $this->success = true;
            } catch (Yz_Model_Error $ex) {
                // this is required to show the form again instead of an error template
                $this->error = $ex;
            }
        }
        return $this;
    }

    /** get success message on model updated
     *      in addition to AbstractFetch's getErrorMessage
     *  @return string
     */
    protected function getSuccessMessage()
    {
        return ':' . $this->name . ':Success';
    }


    /**
     *  @return this
     *
     */
    protected function assignTemplateParams(\Yz_Template_Interface $t)
    {
        if ($this->error) {
            $t->error = $this->error;
            $t->errorMessage = $this->getErrorMessage();
        } else if ($this->success) {
            $t->successMessage = $this->getSuccessMessage();
        }
        return parent::assignTemplateParams($t);
    }


}